package com.unusap.remote.core.util;

import java.net.URLConnection;
import java.util.Collections;
import java.util.Map;

import sun.misc.BASE64Encoder;

import com.unusap.remote.core.remote.factory.HttpHeadersProvider;
import com.unusap.remote.core.remote.http.CommonHttpConnectionArguments;
import com.unusap.remote.core.remote.http.DefaultURLConnectionPropertySetter;
import com.unusap.remote.core.remote.http.HttpSpecification;
import com.unusap.remote.core.remote.http.URLConnectionPropertySetter;

/**
 * Created by IntelliJ IDEA.
 * User: danson
 * Date: 2009-8-21
 * Time: 10:18:27
 * To change this template use File | Settings | File Templates.
 */
public abstract class URLConnectionPropertyUtils {

    public static void setProperty(URLConnection connection, HttpHeadersProvider httpHeadersProvider, 
    		CommonHttpConnectionArguments connectionArguments) {
    	
        connection.setConnectTimeout(connectionArguments.getConnectTimeout());
        String authorization = "Basic " + base64(connectionArguments.getUser() + ":" + connectionArguments.getPassword());
        connection.setRequestProperty(HttpSpecification.REQUEST_HEADER_AUTHORIZATION, authorization);
        if (httpHeadersProvider == null) {
            httpHeadersProvider = new NullHttpHeadersProvider();
        }
        URLConnectionPropertySetter connectionPropertySetter = new DefaultURLConnectionPropertySetter(connection, httpHeadersProvider);
        connectionPropertySetter.execute();
    }

    private static String base64(String string) {
        return new BASE64Encoder().encode(string.getBytes());
    }

    private static class NullHttpHeadersProvider implements HttpHeadersProvider {
        public Map<String, String> getHeaders() {
            return Collections.emptyMap();
        }
    }

}
